package com.tengju.bff.interfaces.manage.crm.brand.facade;

import com.tengju.bff.interfaces.manage.crm.brand.assembler.BrandAnalysisRankAssembler;
import com.tengju.bff.interfaces.manage.crm.brand.vo.BrandSaleRankForm;
import com.tengju.bff.interfaces.shared.*;
import com.tengju.data.domain.model.analysis.Meta;
import com.tengju.data.domain.model.analysis.MetaHolder;
import com.tengju.data.domain.model.analysis.Row;
import com.tengju.data.domain.model.brand.BrandSaleRankFormFactory;
import com.tengju.data.domain.model.brand.BrandSaleRankQueryForm;
import com.tengju.data.domain.model.clickhouse.CrmRankCrowdPerspective;
import com.tengju.data.domain.model.clickhouse.DwsCrmBrandAnalysisDRepository;
import com.tengju.data.domain.model.user.DominationDetailRepository;
import com.tengju.data.domain.model.user.DominationLevelEnum;
import com.tengju.data.domain.model.user.UserIdCode;
import com.tengju.data.domain.shared.CastUtil;
import com.tengju.user.application.user.UserDocumentService;
import com.tengju.user.application.user.dto.UserSearchForm;
import com.tengju.user.domain.model.club.ClubId;
import com.tengju.user.domain.model.club.ClubMemberRepository;
import com.tengju.user.domain.model.doc.UserDocument;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class BrandAnalysisRankFacade {

    private final DominationDetailRepository dominationDetailRepository;
    private final ClubMemberRepository clubMemberRepository;
    private final DwsCrmBrandAnalysisDRepository dwsCrmBrandAnalysisDRepository;
    private final MetaHolder metaHolder;
    private final UserDocumentService userDocumentService;

    @Autowired
    public BrandAnalysisRankFacade(DominationDetailRepository dominationDetailRepository, ClubMemberRepository clubMemberRepository, DwsCrmBrandAnalysisDRepository dwsCrmBrandAnalysisDRepository, MetaHolder metaHolder, UserDocumentService userDocumentService) {
        this.dominationDetailRepository = dominationDetailRepository;
        this.clubMemberRepository = clubMemberRepository;
        this.dwsCrmBrandAnalysisDRepository = dwsCrmBrandAnalysisDRepository;
        this.metaHolder = metaHolder;
        this.userDocumentService = userDocumentService;
    }

    public TableVO brandSaleRank(BrandSaleRankForm brandSaleRankForm, List<UserIdCode> genSecIdCodes) {

        //无管理sec线
        if (CollectionUtils.isEmpty(genSecIdCodes)) {
            return null;
        }

        //根据俱乐部筛选sec线
        if (brandSaleRankForm.getClubId() != null && brandSaleRankForm.getClubId() > 0) {
            List<com.tengju.user.domain.model.user.UserIdCode> members =
                    clubMemberRepository.getMembers(new ClubId(brandSaleRankForm.getClubId()));
            List<UserIdCode> dataMembers = members.stream()
                    .map(com.tengju.user.domain.model.user.UserIdCode::getValue)
                    .map(UserIdCode::new).collect(Collectors.toList());
            //管理sec线 与 club下的sec成员 取交集
            genSecIdCodes.retainAll(dataMembers);
            if (CollectionUtils.isEmpty(genSecIdCodes)) {
                return null;
            }

        }

        UserIdCode dominationIdCode = null;
        DominationLevelEnum dominationLevel = null;
        //所属sec
        if (brandSaleRankForm.getBelongSecIdCode() != null) {
            UserIdCode secIdCode = new UserIdCode(brandSaleRankForm.getBelongSecIdCode());
            //该sec不在管理sec线内 返回null
            if (!genSecIdCodes.contains(secIdCode)) {
                return null;
            }
            dominationIdCode = secIdCode;
            dominationLevel = DominationLevelEnum.GEN_SEC;
        }
        //所属ec
        if (brandSaleRankForm.getBelongEcIdCode() != null) {
            if (brandSaleRankForm.getBelongSecIdCode() == null) {
                throw new InterfaceException(InterfaceCode.PARAM_ERROR);
            }
            //判断EC是否是 该sec的管辖团队内的成员  若不是 直接返回null
            UserIdCode idCode = new UserIdCode(brandSaleRankForm.getBelongEcIdCode());
            UserIdCode secIdCode = new UserIdCode(brandSaleRankForm.getBelongSecIdCode());
            if (!dominationDetailRepository.isDominationMember(idCode, secIdCode, DominationLevelEnum.GEN_SEC)) {
                return null;
            }
            dominationIdCode = idCode;
            dominationLevel = DominationLevelEnum.EC;
        }

        BrandSaleRankQueryForm form = BrandSaleRankFormFactory.create(genSecIdCodes,brandSaleRankForm.getBrandId(),
                brandSaleRankForm.getDateType(), brandSaleRankForm.getCrowdPerspective(), dominationIdCode,
                dominationLevel, brandSaleRankForm.getIdCode(), brandSaleRankForm.getSaleMoneyFrom(),
                brandSaleRankForm.getSaleMoneyTo(), brandSaleRankForm.isDirect(),
                brandSaleRankForm.getOrderColumn(),brandSaleRankForm.getOrderType());

        Integer total = dwsCrmBrandAnalysisDRepository.count(form);
        if (brandSaleRankForm.getOffset() > total) {
            return null;
        }

        form.setOffset(brandSaleRankForm.getOffset());
        form.setPageSize(brandSaleRankForm.getPageSize());
        List<Row> rows = dwsCrmBrandAnalysisDRepository.brandAnalysis(form);


        if (CollectionUtils.isEmpty(rows)) {
            return null;
        }

        //获取idCode
        List<com.tengju.user.domain.model.user.UserIdCode> idCodeList = rows.stream()
                .map(v -> v.getValue("id_code"))
                .map(v -> com.tengju.user.domain.model.user.UserIdCode.of(CastUtil.castLong(v)))
                .collect(Collectors.toList());

        UserSearchForm userSearchForm = new UserSearchForm();
        userSearchForm.setIdCodes(idCodeList);
        List<UserDocument> userDocumentList = userDocumentService.batchSearchScroll(userSearchForm);
        List<UserDocument> leaderDocumentList = null;

        //  城市视角/EC视角 获取上级用户信息
        if (CrmRankCrowdPerspective.CITY_STAR == form.getCrmRankCrowdDatePerspective().getCrmRankCrowdPerspective()
                || CrmRankCrowdPerspective.DEALER == form.getCrmRankCrowdDatePerspective().getCrmRankCrowdPerspective()) {

            if (!CollectionUtils.isEmpty(userDocumentList)) {
                idCodeList = userDocumentList.stream()
                        .map(v -> form.getCrmRankCrowdDatePerspective().getCrmRankCrowdPerspective() == CrmRankCrowdPerspective.DEALER ?
                                List.of(v.getOwnerCityIdCode(), v.getOwnerEcIdCode()) : List.of(v.getOwnerEcIdCode())
                        )
                        .flatMap(Collection::stream)
                        .map(com.tengju.user.domain.model.user.UserIdCode::of)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());}

            if (!CollectionUtils.isEmpty(idCodeList)) {
                userSearchForm.setIdCodes(idCodeList);
                userSearchForm.setScrollId(null);
                leaderDocumentList = userDocumentService.batchSearchScroll(userSearchForm);
            }


        }

        //生成table表头
        TableVO table = new TableVO();
        Collection<Meta> bizMetas = metaHolder.listMeta("brand_sale_list").values();
        TableAssembler.buildColumns(table, bizMetas);

        //封装默认的表格数据
        table.page(total,form.getPageIndex(),form.getPageSize());

        return BrandAnalysisRankAssembler.convertToVo(rows,table, userDocumentList,
                leaderDocumentList, form.getCrmRankCrowdDatePerspective().getCrmRankCrowdPerspective());

    }

    public String totalBrandSale(BrandSaleRankForm brandSaleRankForm, List<UserIdCode> genSecIdCodes) {

        //无管理sec线
        if (CollectionUtils.isEmpty(genSecIdCodes)) {
            return "0";
        }

        //根据俱乐部筛选sec线
        if (brandSaleRankForm.getClubId() != null && brandSaleRankForm.getClubId() > 0) {
            List<com.tengju.user.domain.model.user.UserIdCode> members =
                    clubMemberRepository.getMembers(new ClubId(brandSaleRankForm.getClubId()));
            List<UserIdCode> dataMembers = members.stream()
                    .map(com.tengju.user.domain.model.user.UserIdCode::getValue)
                    .map(UserIdCode::new).collect(Collectors.toList());
            //管理sec线 与 club下的sec成员 取交集
            genSecIdCodes.retainAll(dataMembers);
            if (CollectionUtils.isEmpty(genSecIdCodes)) {
                return "0";
            }

        }

        UserIdCode dominationIdCode = null;
        DominationLevelEnum dominationLevel = null;
        //所属sec
        if (brandSaleRankForm.getBelongSecIdCode() != null) {
            UserIdCode secIdCode = new UserIdCode(brandSaleRankForm.getBelongSecIdCode());
            //该sec不在管理sec线内 返回null
            if (!genSecIdCodes.contains(secIdCode)) {
                return "0";
            }
            dominationIdCode = secIdCode;
            dominationLevel = DominationLevelEnum.GEN_SEC;
        }
        //所属ec
        if (brandSaleRankForm.getBelongEcIdCode() != null) {
            if (brandSaleRankForm.getBelongSecIdCode() == null) {
                throw new InterfaceException(InterfaceCode.PARAM_ERROR);
            }
            //判断EC是否是 该sec的管辖团队内的成员  若不是 直接返回null
            UserIdCode idCode = new UserIdCode(brandSaleRankForm.getBelongEcIdCode());
            UserIdCode secIdCode = new UserIdCode(brandSaleRankForm.getBelongSecIdCode());
            if (!dominationDetailRepository.isDominationMember(idCode, secIdCode, DominationLevelEnum.GEN_SEC)) {
                return "0";
            }
            dominationIdCode = idCode;
            dominationLevel = DominationLevelEnum.EC;
        }

        BrandSaleRankQueryForm form = BrandSaleRankFormFactory.create(genSecIdCodes,brandSaleRankForm.getBrandId(),
                brandSaleRankForm.getDateType(), brandSaleRankForm.getCrowdPerspective(), dominationIdCode,
                dominationLevel, brandSaleRankForm.getIdCode(), brandSaleRankForm.getSaleMoneyFrom(),
                brandSaleRankForm.getSaleMoneyTo(), brandSaleRankForm.isDirect(),
                brandSaleRankForm.getOrderColumn(),brandSaleRankForm.getOrderType());

        BigDecimal totalBrandSale = dwsCrmBrandAnalysisDRepository.totalSaleMoney(form);

        return Formatter.thousandMoney(totalBrandSale.setScale(0, RoundingMode.HALF_UP).intValue());
    }




}
